package br.heusser.productfx.src.dao;

import br.heusser.productfx.src.model.Sale;
import java.util.Date;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.Query;

/**
 * @author Diego Heusser
 */
public class SaleDAO extends DAO{
    
    public void insert(Sale sale) throws Exception {
        EntityManager em = this.getEM();
        try {
            em.getTransaction().begin();
            em.persist(sale);
            em.getTransaction().commit();
        } catch(Exception ex) {
            throw ex;
        } finally {
            em.close();
        }
    }
    
    public void update(Sale sale) throws Exception {
        EntityManager em = this.getEM();
        try{
            em.getTransaction().begin();
            em.merge(sale);
            em.getTransaction().commit();
        } catch(Exception ex) {
            throw ex;
        } finally {
            em.close();
        }
    }
    
    public void delete(Sale sale) throws Exception {
        EntityManager em = this.getEM();
        try {
            em.getTransaction().begin();
            em.remove(sale);
            em.getTransaction().commit();
        } catch(Exception ex) {
            throw ex;
        } finally {
            em.close();
        }
    }
    
    public List<Sale> list() throws Exception {
        EntityManager em = this.getEM();
        try {
            Query query = em.createQuery("SELECT s FROM Sale s");
            List<Sale> list = query.getResultList();
            return list;
        } catch(Exception ex) {
            throw ex;
        } finally {
            em.close();
        }
    }
    
    public List<Sale> find(Date begin, Date end) throws Exception {
        EntityManager em = this.getEM();
        try {
            Query query = em.createQuery("SELECT s FROM Sale s WHERE s.date BETWEEN :begin AND :end");
            query.setParameter("begin", begin);
            query.setParameter("end", end);
            List<Sale> list = query.getResultList();
            return list;
        } catch(Exception ex) {
            throw ex;
        } finally {
            em.close();
        }
    }
}
